package eu.jba.denshijisho.algorithm;

import java.util.Date;

import eu.jba.denshijisho.entity.Card;
import eu.jba.denshijisho.util.Util;

public class Algorithm {

	private static double countNewEf(double oldEF, Integer grade){
		double newEF = oldEF + (0.1f - (5 - grade) * (0.08f + (5 - grade) * 0.02f));
		if( newEF < 1.3){
			return 1.3;
		}else{
			return newEF;
		}
	}
	
	private static int countInterval( int reps, double ef){
		return (int)Math.round((reps - 1) * ef);
	}
	
	public static void calcIntervalEF(Card card, Integer grade){
        double oldEF = card.getStat().getEf();
        double newEF = countNewEf( oldEF, grade);
        card.getStat().setWrongAnswers(card.getStat().getWrongAnswers() + 1);
        card.getStat().setReps(card.getStat().getReps() + 1);
        
        if (grade == 1) {
            card.getStat().setInterval(1);
            card.getStat().setEf( newEF );
        } else {
            card.getStat().setEf( newEF );
            
            switch (card.getStat().getReps().intValue()) {
                case 1:
                    card.getStat().setInterval(1);
                    break;
                case 2:
                    card.getStat().setInterval(3);
                    break;
                default:
                    card.getStat().setInterval(countInterval(card.getStat().getInterval(), newEF ) );
                    break;
            }
        }
        final Date today = new Date();
        card.getStat().setNextDate(
			Util.convertToDate(
				today.getTime() + Util.convertToMilliseconds( card.getStat().getInterval() )
			)
        );
    }
}
